<?php
/**
 * *********************************************************************************************************************
 * 通过单号查询对应收件人的手机号和手机地址
 * *********************************************************************************************************************
 */
namespace soa\parter\sto;

use artisan\cache;
use artisan\http;
use soa\client;
use soa\partner\DeliveryCommon;

class mobileAddress extends client
{

    /**
     * 服务地址
     * @var string
     */
    protected $my_service_url = 'http://222.66.109.133:22225/stokb/recipientByBillNo.action';   //老接口

    public static $serviceUrl = 'http://stokb.sto-express.cn:22228/recipientphone/recipientByBillNo.action';   //新接口

//    protected $my_service_url = 'http://222.66.109.133:22226/stokb/recipientByBillNo.action';   //测试地址，返回省市区信息

    /**
     * 快宝服务
     * @var string
     */
    protected $service_url = 'http://express.core.kuaidihelp.com/';

    /**
     * 服务项目名称
     * @var string
     */
    protected $service_name = 'kuaidihelp_sto';

    public function getServiceUrl()
    {
        return $this->service_url;
    }

    public function getMyServiceUrl()
    {
        return $this->my_service_url;
    }

    /**
     * 通过单号查询收件人手机号，姓名，收件地址
     * @param array $waybillNos
     * @return array|string
     */
    public function ast($waybillNos, $cmPhone = '', $cmId = 0, $empNo = '', $type = 'address')
    {
        $this->my_service_url = self::$serviceUrl;

        if (empty($waybillNos) && !is_array($waybillNos))
            return array();

//        array_walk($waybillNos, function (&$item) {
//            $item = trim($item);
//        });

        if(('phone' == $type && 1 == count($waybillNos)) || !in_array($type,array('address','phone'))){
            $type = 'address';  //type为phone不写入数据库,单条时写入数据库
        }

        $isEdit = 0;
        $return = $insertToDB = array();

        //1、从cache查数据
        if($cmPhone){
            $cacheKey = 'sto_address_info_' . $cmPhone . '-' . date('Y-m-d');
            $resultsFromCache = cache::connect('pda')->get($cacheKey);
            if(!empty($resultsFromCache) && is_array($resultsFromCache)){
                foreach($waybillNos as $waybillNo){
                    if(isset($resultsFromCache[$waybillNo]) && is_array($resultsFromCache[$waybillNo])){
                        $info = $this->getRequest($type,$waybillNo,$resultsFromCache[$waybillNo]);
                        if($info){
                            $return[$waybillNo] = $info;
                        }
                    }
                }

                $waybillNos = array_merge(array_diff($waybillNos,array_keys($return)));
            }
        }

        $resultsFromCache = isset($resultsFromCache) && is_array($resultsFromCache) && $resultsFromCache ? $resultsFromCache : [];

        //2、从数据库查数据
        if(!empty($waybillNos)){
            $resultsFromDb = $this->post('/v1/parter/sto/getMobileAddressByDB', array('waybillNo' =>$waybillNos,'type'=>$type));
        }

        if(!empty($resultsFromDb) && is_array($resultsFromDb)){
           foreach ($resultsFromDb as $waybillNo => $result) {
               $return[$waybillNo] = $this->getRequest($type,$waybillNo,$result);

               if(!empty($result['phone']) || !empty($result['address'])){
                   $isEdit = 1;
                   $resultsFromCache[$waybillNo] = !empty($resultsFromCache[$waybillNo])?$resultsFromCache[$waybillNo]:[];
                   $resultsFromCache[$waybillNo] = $this->getRequest('cache',$waybillNo,$resultsFromCache[$waybillNo],$result);
               }
           }

           $waybillNos = array_merge(array_diff($waybillNos, array_keys($resultsFromDb)));
           unset($resultsFromDb);
        }

        //3、从接口查数据
        if(!empty($waybillNos)){
            $results = $this->getAddress($waybillNos);
        }

        if (!empty($results)) {
            $results = json_decode($results, true);

            if (json_last_error() == 0) {
                foreach ($results as $result) {
                    $waybillNo = $result['waybill'];
                    $info = $this->getRequest($type,$waybillNo,$result);
                    if($info){
                        $return[$waybillNo] = $insertToDB[$waybillNo] = $info;
                        $insertToDB[$waybillNo]['info']['cm_phone'] = !empty($cmPhone)?$cmPhone:'';
                        $insertToDB[$waybillNo]['info']['emp_no'] = !empty($empNo)?$empNo:'';
                    }
                    if(!empty($result['phone']) || !empty($result['address'])){
                        $isEdit = 1;
                        $resultsFromCache[$waybillNo] = !empty($resultsFromCache[$waybillNo])?$resultsFromCache[$waybillNo]:[];
                        $resultsFromCache[$waybillNo] = $this->getRequest('cache',$waybillNo,$resultsFromCache[$waybillNo],$result);
                    }
                }

                unset($results);
                if('address' == $type && $insertToDB){
                    (new DeliveryCommon())->logMobileAddress('sto',$insertToDB);
//                    later(function() use ($insertToDB) {
//                        $this->post('/v1/parter/sto/getMobileAddressByWaybillNo', array('info' => array_values($insertToDB)));
//                    });
                }
            }
        }

        if(isset($cacheKey) && $isEdit && $resultsFromCache){
            cache::connect('pda')->set($cacheKey,$resultsFromCache);
            cache::connect('pda')->expireat($cacheKey, strtotime(date('Y-m-d') . ' + 1 day'));
        }

        return $return;
    }

    /**
     * 从数据库拿数据
     * @param array $waybillNos
     * @return array|bool|null
     */
    public function DB(array $waybillNos)
    {
        if (empty($waybillNos) && !is_array($waybillNos))
            return array();

        array_walk($waybillNos, function (&$item) {
            $item = trim($item);
        });

        return $this->get('/v1/parter/sto/getMobileAddressByDB', array('waybillNo' => implode(',', $waybillNos)));
    }

    public function getAddress($waybillNos)
    {
        //双11临时屏蔽
        $block = 0;//要屏蔽改成1
        if($block && (time() > strtotime(date('Y-m-d 06:00:00')) || time() < strtotime(date('Y-m-d 23:00:00')))){
            return array();
        }
$time1 = time();
        if(empty($waybillNos) && !is_array($waybillNos)){
            return array();
        }

        $results = http::post(self::getUrl(), array('billCodes' => implode(',', $waybillNos)), ['TIMEOUT'=>5]);
//        logDebug($results,'sto_addr',time()-$time1);
        return $results;
    }

    public function getRequest($type,$waybillNo,$data,$dataEx=[])
    {
        if('phone' == $type){
            if(empty($data['phone'])){
                return [];
            }
            return array(
                'waybillNo' => (string)$waybillNo,
                'info'      => array(
                    'phone' => !empty($data['phone']) && !in_array($data['phone'],['1**********'])? $data['phone'] : '',
                )
            );
        } elseif ('cache' == $type) {
            return array(
                'name'     => !empty($data['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $data['name']) : (!empty($dataEx['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $dataEx['name']) : ''),
                'phone'    => !empty($data['phone']) ? $data['phone'] : (!empty($dataEx['phone']) ? $dataEx['phone'] : ''),
                'province' => !empty($data['province']) ? $data['province'] : (!empty($dataEx['province']) ? $dataEx['province'] : ''),
                'city'     => !empty($data['city']) ? $data['city'] : (!empty($dataEx['city']) ? $dataEx['city'] : ''),
                'area'     => !empty($data['area']) ? $data['area'] : (!empty($dataEx['area']) ? $dataEx['area'] : ''),
                'address'  => !empty($data['address']) ? $data['address'] : (!empty($dataEx['address']) ? $dataEx['address'] : ''),
            );
        } else {
            if(empty($data['address'])){
                return [];
            }
            return array(
                'waybillNo' => (string)$waybillNo,
                'info'      => array(
                    'name'     => !empty($data['name']) ? preg_replace("/[ ;*?~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", '', $data['name']) : '',
                    'phone'    => !empty($data['phone']) && !in_array($data['phone'],['1**********'])? $data['phone'] : '',
                    'province' => !empty($data['province']) ? $data['province'] : '',
                    'city'     => !empty($data['city']) ? $data['city'] : '',
                    'area'     => !empty($data['area']) ? $data['area'] : '',
                    'address'  => !empty($data['address']) ? $data['address'] : '',
                )
            );
        }
    }

    public static function getUrl()
    {
        return self::$serviceUrl;
    }
}
